package com.example.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {
    public static long Time = 30*60*1000;       //设置过期时间
    private static java.security.Key Key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("XL80a0zLwVL3DA+jj6ubCHXMij1R1Yp0CFAkV32JIBo="));//生成一个密钥  ，为加密前的签名


    public static String genJwt(Map<String,Object>claims){       //这个方法生成一个令牌
        //生成安全密钥   为加密前的签名
//        SecretKey Key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("bnqgCcgkbooCxKFJSoi3j1/EvNCItlbjmS8YHIVBv7I="));
        //自定义信息
//        Map<String,Object> claim = new HashMap<>();
//        claim.put("id",1);
//        claim.put("username","zhangsan");

        return Jwts.builder()
                .setClaims(claims)   //自定义内容负载
                .signWith(Key)  //根据生成的密钥设置签名算法
                .setExpiration(new Date(System.currentTimeMillis()+Time))
                .compact();     //类似与结束的标志

//        System.out.println(jwt);

    }

    public static void genKey(){   //这个方法生成一个密钥
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(encode);

    }

    public static Claims parseJWT(String token){     //校验令牌

        //String token = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ6aGFuZ3NhbiIsImV4cCI6MTcyMzI5MTA3M30.LPeNsX2xIDcycMOU9xUqUgpSuOGDL7TgTpG2C8i7NFY";
        //创建解析器，设置签名密钥
        JwtParser Builder = Jwts.parserBuilder().setSigningKey(Key).build();
        //解析token
        Claims claims = null;
        try{
            claims=Builder.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("校验失败:" + token);
        }

        return claims;
    }


    public static Integer getUserIdFromToken(String jwttoken){
       Claims claims = parseJWT(jwttoken);
       Integer userId = (Integer) claims.get("id");

       return userId;


    }




}
